package xyz.zhouxf.rpc.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import xyz.zhouxf.rpc.entity.RpcRequest;
import xyz.zhouxf.rpc.enumeration.CommonEnum;
import xyz.zhouxf.rpc.enumeration.PackageType;
import xyz.zhouxf.rpc.serializer.RpcSerializer;

/**
 * 编码器
 * @author zhouxf
 * @date 2022/8/20
 */
public class CommonEncoder extends MessageToByteEncoder {

    private static final int MAGIC_NUMBER = CommonEnum.MAGIC_NUMBER.getCode();

    private final RpcSerializer serializer;

    public CommonEncoder(RpcSerializer serializer) {
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) {
        byteBuf.writeShort(MAGIC_NUMBER);
        if(o instanceof RpcRequest) {
            byteBuf.writeByte(PackageType.REQUEST.getCode());
        }else {
            byteBuf.writeByte(PackageType.RESPONSE.getCode());
        }
        byteBuf.writeByte(serializer.getCode());
        byte[] bytes = serializer.serialize(o);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
